shell 练习-判断80端口是否开启

写一个脚本,判断本机的80端口是否开启着,如果开启着什么都不做,如果发现端口不存在,那么重启一下httpd服务,并发邮件通知你自己。脚本写好后,可以每一分钟执行一次,也可以写一个死循环的脚本,30s检测一次。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#!/bin/bash
mail=123@123.com
if netstat -lnp|grep ':80'|grep -q 'LISTEN'
then
exit
else
/usr/local/apache2/bin/apachectl restart > /dev/null 2> /dev/null
echo "The 80 port is down."|mail -s 'check_80' $mail
n=`pa aux|grep httpd|grep -cv grep`
if [$n -eq 0 ]
then
/usr/local/apache2/bin/apachectl start 2> tmp/apache_start.err
fi
if [ -s /tmp/apache_start.err ]
then
mail -s 'apache_start_error' $mail < /tmp/apache_start.err
fi
fi

        脚本用 crontab -e 加入任务计划,每分钟执行一次

        也可以用 while 死循环

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!/bin/bash
mail=123@123.com
while :
do
if netstat -lnp|grep ':80'|grep -q 'LISTEN'
then
exit
else
/usr/local/apache2/bin/apachectl restart > /dev/null 2> /dev/null
echo "The 80 port is down."|mail -s 'check_80' $mail
n=`pa aux|grep httpd|grep -cv grep`
if [$n -eq 0 ]
then
/usr/local/apache2/bin/apachectl start 2> tmp/apache_start.err
fi
if [ -s /tmp/apache_start.err ]
then
mail -s 'apache_start_error' $mail < /tmp/apache_start.err
fi
fi
sleep 30
done